<?php

namespace app\api\controller;

use app\api\BaseController;
use app\model\ReportImgModel;
use app\model\ReportModel;
use app\model\UserModel;

class Report extends BaseController
{
    public function queryList()
    {
//        $params = $this->request->param();
        $userinfo = $this->request->userInfo;

        $list = ReportModel::where('user_id',$userinfo['userId'])
            ->order([
                'status' => 'asc',
                'submit_time' => 'desc'
            ])
            ->select();
        return show($list);
    }
    public function add()
    {
        $params = $this->request->param();

        $userinfo = $this->request->userInfo;

        if (empty($params['content'])) {
            return show([],1,'缺少内容');
        }

        if (empty($params['fileList'])) {
            return show([],1,'缺少图片');
        }

        if (empty($params['location'])) {
            return show([],1,'缺少位置');
        }

        $userModel = UserModel::find($userinfo['userId']);

        $reportModel = ReportModel::create([
            'content' => $params['content'],
            'submit_time' => time(),
            'status' => 1,  // 1:待受理2:已受理3:已完成
            'user_id' => $userinfo['userId'],
            'admin_id' => $userModel->admin_id,
            'location' => json_encode($params['location'])
        ]);

        $id = $reportModel->id;

        $imgIds= array_map(function ($item) use ($id){
            return [
                'report_id' => $id,
                'id' => $item['id']
            ];
        }, $params['fileList']);

        $reportImgModel = new ReportImgModel();
        $reportImgModel->saveAll($imgIds);

        return show();
    }

    public function del()
    {
        $params = $this->request->param();

        if (empty($params['id'])) {
            return show([],1,'缺少id');
        }

        ReportModel::destroy($params['id']);

        return show();


    }

    public function delImg()
    {
        $params = $this->request->param();

        if (empty($params['id'])) {
            return show([],1,'缺少参数id');
        }
        $reportImgModel = ReportImgModel::find($params['id']);

        if ($reportImgModel === null) {
            return show([],1,'已删除');
        }

        $reportImgModel->delete();

        return show();

    }

    public function details()
    {
        $params = $this->request->param();

        if (empty($params['id'])) {
            return show([],1,'缺少参数id');
        }

        $reportModel = ReportModel::with('img')->where('id',$params['id'])->find();

        return show($reportModel);

    }
}